<template>
  <div>
    <a-modal :visible="visible" :title="title" :bodyStyle="{
      padding: '0px 20px',
    }" @cancel="cancelClick" :footer="null" :width="1000" :destroyOnClose="true">
      <a-card :bordered="false">
        <div class="textarea-wrapper">
          <a-textarea :bordered="false" v-model:value="content" :autoSize="{ minRows: 4 }" :maxlength="500" show-count
            @change="textareaChange" />
          <div class="mask-text" v-if="isIndicator">
            <a-spin :indicator="indicator" />
            <div class="mask-box">音频合成中，请稍后...</div>
          </div>
        </div>
        <div class="dubbing">
          <div>
            <a-tabs v-model:activeKey="activeKey" @change="activeChange">
              <a-tab-pane v-for="tab in tabList" :key="tab.key" :tab="tab.value" />
            </a-tabs>
            <a-spin tip="加载中..." :spinning="loading">
              <div class="voice-content hide-scroller-bar">
                <div class="n-tab-pane" v-for="voice in voiceList" :key="voice.gender_type">
                  <div class="group-name">{{ voice.gender_title }}：</div>
                  <a-row style="flex: 1" :wrap="true">
                    <a-col v-for="item in voice.item" :key="item.id" @click="voiceClick(item)">
                      <div class="group-box" :class="timbreId == item.timbre_id ? 'group-border' : ''
                        ">
                        <div class="right-badge" v-if="item.quality == 2">
                          <cu-icon type="icon-zuanshihuiyuan" style="font-size: 18px" />
                          精品
                        </div>
                        <div class="avatar">
                          <a-avatar :src="item.img" />
                          <div class="mask" @click="playbackClick(item)">
                            <cu-icon class="icon" :type="!item.isPlay ? 'icon-bofang1' : 'icon-zanting'
                              " />
                          </div>
                        </div>
                        <div>
                          <div>{{ item.name }}</div>
                          <div>{{ item.human_style }}</div>
                        </div>
                      </div>
                    </a-col>
                  </a-row>
                </div>
              </div>
            </a-spin>
          </div>
        </div>
        <div class="voice">
          <a-row align="middle" :gutter="[0, 16]">
            <a-col :span="24">
              <div class="voice-item">
                <div class="copywriting-title">语气：</div>
                <a-select v-model:value="emotion_category" placeholder="请选择" style="width: 100%"
                  :disabled="toneDisabled">
                  <a-select-option v-for="item in toneList" :value="item.key" :key="item.key">
                    {{ item.value }}
                  </a-select-option>
                </a-select>
              </div>
            </a-col>
            <a-col :span="24">
              <a-space>
                <div>语速：</div>
                <a-slider v-model:value="speed" :max="2" :min="-2" />
                <a-input-number id="inputNumber" v-model:value="speed" :min="-2" :max="2" size="small"
                  style="width: 60px; margin-left: 30px" />
              </a-space>
            </a-col>

            <a-col :span="24">
              <a-space>
                <div>音量：</div>
                <a-slider v-model:value="volume" :max="11" :min="1" style="margin-right: 120px" />
                <a-input-number id="inputNumber" v-model:value="volume" :min="1" :max="11" size="small"
                  style="width: 60px; margin-left: 30px" />
              </a-space>
            </a-col>
            <a-col :span="24">
              <a-space>
                <div>情感：</div>
                <a-slider v-model:value="emotion_intensity" :max="200" :min="50" />
                <a-input-number id="inputNumber" v-model:value="emotion_intensity" :max="200" :min="50" size="small"
                  style="width: 60px; margin-left: 30px" />
              </a-space>
            </a-col>
          </a-row>
        </div>
      </a-card>
      <div class="footer">
        <div class="operation">
          <div class="flex align-center">
            <a-col class="auto-box">
              <audio-player v-if="isResultUrl" ref="audioPlayer" class="audio-box" :fileurl="isResultUrl"
                :playNum="playNum" :index="1" @audioStatus="audioStatus" @setAudio="setAudio" />
            </a-col>
            <a-space>
              <a-button type="primary" @click="playAutoClick" :loading="isIndicator">
                {{ isPlay ? "播放" : "暂停" }}
              </a-button>
              <a-button type="primary" v-if="isResultUrl" @click="saveMaterials">
                保存到素材
              </a-button>
              <a-button type="primary" v-if="isResultUrl" ghost :loading="soundLoading" @click="downloadSound">
                下载声音
              </a-button>
            </a-space>
          </div>
        </div>
      </div>
    </a-modal>

    <!-- 保存到素材弹框 -->
    <MaterialsModule :visible="visibleMaterials" :data="materialData" @onCancel="visibleMaterials = false"
      @onSuccess="successMaterials" />
  </div>
</template>

<script>
import {
  defineComponent,
  reactive,
  toRefs,
  nextTick,
  watch,
  ref,
  h,
  computed,
  onMounted
} from "vue";
import {
  CaretRightOutlined,
  PauseCircleFilled,
  LoadingOutlined,
} from "@ant-design/icons-vue";
import { message } from "ant-design-vue";
import dayjs from "dayjs";
import AudioPlayer from "../../../../components/AudioPlayer/index.vue";
import MaterialsModule from "../../../../components/MaterialsModule/index.vue";
import request from "../../../../../../common/utils/request";
import store from "@/store/index";

export default defineComponent({
  name: "AddDubbing",
  components: {
    CaretRightOutlined,
    PauseCircleFilled,
    MaterialsModule,
    AudioPlayer,
  },
  props: {
    visible: {
      type: Boolean,
      default: false,
    },
  },
  setup(props, { emit }) {


    const state = reactive({
      // 语气
      emotion_category: "",
      toneList: [],
      toneDisabled: true,
      // 语速
      speed: 0,
      // 音频情感程度
      emotion_intensity: 150,
      // 音量
      volume: 5,

      loading: false,
      activeKey: "",
      tabList: [],
      voiceList: [],
      voiceData: {},
      timbreId: 0,

      visibleMaterials: false,
      materialData: {},
      appName: '',

      isResultUrl: "",
      playNum: 0,
      content: `欢迎使用${appName.value}视频文字转语音工具`,
      isIndicator: false,
      isPlay: true,
      audioPlayer: null,
      soundLoading: false,
    });

    onMounted(()=>{
      store.dispatch("getAiConfig").then((aiConfig) => {
        state.appName = aiConfig.site_name
        state.content = `欢迎使用${aiConfig.site_name}视频文字转语音工具`
      })
    })
    const getList = () => {
      state.loading = true;
      request
        .get("/work_ai", "/user/shotstack/voice/category")
        .then((res) => {
          state.tabList = res.result;
          state.activeKey = res.result[0].key;
          state.loading = false;
          getVoiceList();
        })
        .catch(() => {
          state.loading = false;
        });
    };

    const getVoiceList = () => {
      state.loading = true;
      request
        .get("/work_ai", "/user/shotstack/voice/list", {
          category: state.activeKey,
        })
        .then((res) => {
          if (res.result.length) {
            state.voiceData = res.result[0].item[0];
            state.timbreId = res.result[0].item[0].timbre_id;
            state.toneList = res.result[0].item[0].emotion_style;
            res.result.forEach((item) => {
              item.item.forEach((sub) => {
                sub.isPlay = false;
              });
            });
            state.voiceList = res.result;
            state.emotion_category = res.result[0].item[0].emotion_style[0].key;
            if (res.result[0].item[0].emotion_style.length == 1) {
              state.toneDisabled = true;
              state.loading = false;

              return;
            }
            state.toneDisabled = false;
          }
          state.loading = false;
        });
    };

    const voiceClick = (data) => {
      state.voiceData = data;
      state.timbreId = data.timbre_id;
      state.emotion_category = data.emotion_style[0].key;
      state.toneList = data.emotion_style;
      if (data.emotion_style.length == 1) {
        state.toneDisabled = true;
        return;
      }
      state.toneDisabled = false;
    };

    const activeChange = () => {
      getVoiceList();
    };

    // 播放/暂停
    const playbackClick = (data) => {
      data.isPlay = !data.isPlay;
      if (data.isPlay) {
        if (state.audioPlayer) {
          state.audioPlayer.pause(); // 暂停当前播放的音频
          state.audioPlayer.src = "";
        }
        state.audioPlayer = new Audio(data.voice_url); // 播放下一个音频文件
        state.audioPlayer.play(); // 开始播放音频
      } else {
        state.audioPlayer.src = "";
        state.audioPlayer.pause();
      }
      state.voiceList.forEach((voice) => {
        if (voice.item) {
          voice.item.forEach((item) => {
            if (item.id !== data.id) {
              item.isPlay = false;
            }
          });
        }
      });
      if (state.audioPlayer) {
        state.audioPlayer.addEventListener("ended", function () {
          // 这里写入结束回调函数的代码
          console.log("结束语音");
          state.voiceList.forEach((voice) => {
            if (voice.item) {
              voice.item.forEach((item) => {
                if (item.id == data.id) {
                  item.isPlay = false;
                }
              });
            }
          });
        });
      }
    };

    // 播放文案
    const playAutoClick = () => {
      if (state.isResultUrl) {
        state.isPlay = !state.isPlay;
        state.playNum++;
        return;
      }
      if (!state.content) {
        message.warn("请输入文案");
        return;
      }

      let params = {
        text: state.content,
        speed: state.speed,
        timbre_id: state.timbreId,
        volume: state.volume - 1,
        emotion_category: state.emotion_category,
        emotion_intensity: state.emotion_intensity,
      };
      state.isIndicator = true;
      request
        .get("/work_ai", "/user/shotstack/textToVoice", params)
        .then((res) => {
          let tiem = setInterval(() => {
            request
              .get("/work_ai", "/user/shotstack/getVoice", {
                task_id: res.result.task_id,
                request_id: res.result.request_id || ''
              })
              .then((task) => {
                if (task.result.Data.ResultUrl) {
                  state.isResultUrl = task.result.Data.ResultUrl;
                  state.isIndicator = false;
                  state.isPlay = false;
                  clearInterval(tiem);
                }
              });
          }, 1000);
        });
    };

    const audioStatus = (status) => {
      if (status) {
        state.isPlay = true;
      }
    };

    const setAudio = () => {
      state.isPlay = false;
    };

    // 监听输入框变化
    const textareaChange = () => {
      state.isResultUrl = "";
    };

    // 保存到素材
    const saveMaterials = () => {
      state.materialData.autoName = `${state.voiceData.name}_${state.voiceData.human_style
        }_${dayjs().format("YYYYMMDDHHmmss")}.mp3`;
      state.materialData.material_url = state.isResultUrl;
      state.visibleMaterials = true;
    };

    const successMaterials = () => {
      state.visibleMaterials = false;
      emit("successMaterial", true);
    };

    // 下载声音
    const downloadSound = () => {
      state.soundLoading = true;
      request
        .downLoad("/work_ai", "/user/shotstack/download/file", {
          file_url: state.isResultUrl,
          file_name: `${state.voiceData.name}_${state.voiceData.human_style
            }_${dayjs().format("YYYYMMDDHHmmss")}.mp3`,
        })
        .then((res) => {
          let url = window.URL.createObjectURL(new Blob([res.data]));
          let link = document.createElement("a");
          link.style.display = "none";
          link.href = url;
          link.setAttribute("download", res.fileName || "");
          document.body.appendChild(link);
          link.click();
          state.soundLoading = false;
        })
        .catch((err) => {
          message.error("下载失败");
          state.soundLoading = false;
        });
    };

    const indicator = h(LoadingOutlined, {
      style: {
        fontSize: "30px",
      },
      spin: true,
    });

    const cancelClick = () => {
      emit("onCancel");
    };

    watch(
      () => props.visible,
      (val) => {
        if (val) {
          getList();
        } else {
          state.isResultUrl = "";
          state.playNum = 0;
          state.content = `欢迎使用${state.appName}视频文字转语音工具`;
          state.isIndicator = false;
          state.isPlay = true;
          state.speed = 0;
          state.emotion_intensity = 150;
          state.volume = 5;
        }
      }
    );

    const title = computed(() => {
      return props.id ? "编辑配音" : "添加配音";
    });

    return {
      ...toRefs(state),
      playbackClick,
      activeChange,
      voiceClick,
      playAutoClick,
      textareaChange,
      downloadSound,
      saveMaterials,
      cancelClick,
      indicator,
      title,
      audioStatus,
      setAudio,
      successMaterials,
    };
  },
});
</script>

<style lang="less" scoped>
.smart-clip {
  padding: 0 20px 20px 20px;
}

button {
  border-radius: 5px;
}

:deep(.ss-select-selector) {
  border-radius: 0 5px 5px 0 !important;
}

.dubbing {
  display: flex;
  width: 100%;
}

.copywriting {
  display: flex;
  margin-bottom: 20px;
}

.dubbing-title,
.copywriting-title {
  display: flex;
  width: 60px;
  padding: 12px 0;
}

.ss-card {
  border-radius: 10px;
  margin: 5px 0;
}

.voice-content {
  width: 100%;
  height: 210px;
  overflow: auto;
}

.n-tab-pane {
  display: flex;

  .group-box {
    display: flex;
    align-items: center;
    width: 185px;
    height: 75px;
    padding: 30px 15px;
    margin-bottom: 20px;
    margin-right: 20px;
    border-radius: 5px;
    border: 1px solid #d9d9d9;
    cursor: pointer;
    position: relative;

    &.group-border {
      border: 1px solid #436ba0;
    }

    .avatar {
      margin-right: 5px;
    }

    .mask {
      position: absolute;
      top: 21px;
      left: 15px;
      width: 32px;
      height: 32px;
      border-radius: 50%;
      background: rgba(0, 0, 0, 0.3);

      .icon {
        margin-left: 8px;
        margin-top: 6px;
        color: #fff;
        font-size: 18px;
      }

      display: none;
    }

    :hover {
      .mask {
        display: block;
      }
    }

    .right-badge {
      position: absolute;
      top: 0;
      right: 0;
      width: auto;
      height: 20px;
      padding: 5px;
      display: flex;
      align-items: center;
      justify-content: center;
      color: #fff;
      font-size: 12px;
      border-radius: 2px;
      background: #ff9c00;
    }
  }
}

.group-title {
  width: 90px;
  // display: flex;
  // justify-content: center;
}

.role_box {
  width: calc(100% - 100px);
  display: flex;
  flex-wrap: wrap;
}

.role_item {
  flex: 0 0 25%;
  height: 40px;
}

:deep(.ss-radio-wrapper) {
  margin-right: 0px;
}

.ss-radio-group {
  width: 100%;
  display: flex;
  flex-wrap: wrap;
}

.group-name {
  width: 80px;
}

.voice {
  margin-top: 15px;
  margin-bottom: 30px;
}

.voice-item {
  width: 100%;
  display: flex;
  align-items: center;
}

.ss-slider {
  width: 780px;
}

.textarea-wrapper {
  width: 100%;
  position: relative;
  border: 1px solid #eaeaea;
  padding: 20px;
  position: relative;

  .mask-text {
    position: absolute;
    top: 0;
    left: 0;
    width: 100%;
    height: 100%;
    background: rgba(255, 255, 255, 0.5);
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;

    .mask-box {
      width: 176px;
      height: 62px;
      background: #d1d5db;
      color: #2878FF;
      display: flex;
      align-items: center;
      justify-content: center;
      margin-top: 15px;
    }
  }
}

.operation {
  display: flex;
  align-items: center;
  justify-content: center;
  height: 60px;
  position: absolute;
  bottom: 0;
  left: 0;
  width: 100%;
  padding: 20px;

  .auto-box {
    margin-right: 10px;
  }
}

.operation-btn {
  font-size: 24px;
  color: #666;
  margin-left: 10px;
  cursor: pointer;
}

.add-btn {
  display: flex;
  justify-content: center;
  align-items: center;
  margin-top: 20px;
  margin-left: 95px;
}

:deep(.ss-card-body) {
  padding-top: 0;
}

.footer {
  width: 100%;
  text-align: center;
}

:deep(.ss-slider) {
  width: 750px;
}
</style>
